package com.toy.core.security.login.web;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.toy.core.config.SysConfig;
import com.toy.core.security.AuthenticatedType;
import com.toy.core.security.Authentication;
import com.toy.core.security.UsernamePasswordAuthentication;
import com.toy.core.security.authenticate.AuthenticationProvider;
import com.toy.core.security.exception.AuthenticationException;
import com.toy.core.util.CookieUtils;

@Controller
@RequestMapping("/client/storage")
public class StorageController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(StorageController.class);
	
	@Autowired
	private AuthenticationProvider authenticationProvider;
	
	@Autowired
	private SysConfig sysConfig;
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request,HttpServletResponse response){
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String target = request.getParameter("target");
		UsernamePasswordAuthentication authentication = new UsernamePasswordAuthentication(username,password);
		authentication.setAttribute(Authentication.ATTR_REMOTEADDR, request.getRemoteAddr());
		authentication.setAttribute(Authentication.ATTR_SESSIONID, request.getSession().getId());
		authentication.setAttribute(Authentication.ATTR_AUTHENTICATED_TYPE, AuthenticatedType.STORAGE);
		try {
			Authentication newAuthentication = authenticationProvider.authenticate(authentication);
			CookieUtils.saveAuthentication(newAuthentication, request, response);
		} catch (AuthenticationException e) {
			if (logger.isDebugEnabled()) {logger.debug("AuthenticationException=" + e);}
			request.setAttribute("error", e.getMessage());
			return "forward:"+ sysConfig.getStorageLoginInputUrl();
		}
		
		if (StringUtils.isNotBlank(target)){
			return "redirect:"+target;
		}
		
		return "redirect:"+sysConfig.getHomePageUrl();
	}
	
}
